﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AssessmentTool.PresentationLogic.Controllers;
using AdminApplication.Controls;
using ModelLayer;
using AssessmentTool.PresentationLogic.EventArguments;
using AdminApplication.ServiceBridge;
using System.ComponentModel;
using AssessmentTool.Services.DTO;
using AssessmentTool.PresentationLogic;

namespace AdminApplication.PresentationLogic.Controllers
{
    public class InsertUserController : AbstractController<InsertUser>
    {
        public InsertUserController(InsertUser element)
            : base(element)
        {
            ed.subscrive("LOGOUT", logout);
            ed.subscrive("USERSELECTED", logout);
            ed.subscrive("SHOWINSERTUSER", load);
        }

        public void logout(EventArgs e)
        {
            element.Visibility = Visibility.Collapsed;
        }
        public void load(EventArgs e)
        {
            element.Visibility = Visibility.Visible;
        }
        public void inserisci()
        {
            Utente u = new Utente();
            
            u.Nome = element.Nome.Text;
            u.Cognome = element.Cognome.Text;
            u.Username = element.Username.Text;
            u.Password = element.Password.Password;
            if (u.Password != element.Conferma.Password)
            {
                ed.dispatch("SHOWMESSAGE", new ShowMessageEventArgs() { Testo = "Le password inserite sono diverse!", Critico = false, Error = true });
                return;
            }
            u.Email = element.Email.Text;
            UtenteLogged logged = (UtenteLogged)Session.getInstance().getValue("USERLOGGED");
            UtenteAdminServiceBridge.inserisciUtente(u,logged.utente, onInsert);
        }
        public void onInsert(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                ed.dispatch("STOPBUSY", new EventArgs());
                ed.dispatch("SHOWMESSAGE", new ShowMessageEventArgs() { Testo = "Errore nell'inserire l'utente. Username già in uso.", Critico = false, Error = true });

            }
            else
            {
                ed.dispatch("SHOWMESSAGE", new ShowMessageEventArgs() { Testo = "Utente inserito!", Critico = false, Error = false });
                ed.dispatch("REFRESHLIST",null);
            }
        }
    }
}
